package cn.org.xiaosheng.ambassado;

import cn.org.xiaosheng.ambassado.interfaces.RemoteServiceInterface;


/**
 * @author XiaoSheng
 * @date 2024/8/1 下午12:33
 */
public class ServiceAmbassador implements RemoteServiceInterface {

    private static final int RETRIES = 3;
    private static final int DELAY_MS = 3000;

    public ServiceAmbassador() {

    }

    @Override
    public long doRemoteFunction(int value) throws Exception {
        return safeCall(value);
    }

    private long checkLatency(int value) throws Exception {
        long startTime = System.currentTimeMillis();
        long result = RemoteService.getRemoteService().doRemoteFunction(value);
        long timeTaken = System.currentTimeMillis() - startTime;

        System.out.println("Time taken (ms): " + timeTaken);
        return result;
    }

    private long safeCall(int value) throws Exception {
        int retries = 0;
        long result = (long) 500;

        for (int i = 0; i < RETRIES; i++) {
            if (retries >= RETRIES) {
                return 500;
            }

            if ((result = checkLatency(value)) == 500) {
                System.out.println("Failed to reach remote: (" + (i + 1) + ")");
                retries++;
                try {
                    Thread.sleep(DELAY_MS);
                } catch (InterruptedException e) {
                    System.out.println("Thread sleep state interrupted" + e);
                }
            } else {
                break;
            }
        }
        return result;
    }

}
